package com.two.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.two.core.entity.course.EduSubject;
import com.two.core.vo.Result;
import com.two.course.dao.SubjectDao;
import com.two.course.service.SubjectService;
import com.two.course.vo.ChangeStatusIdVo;
import com.two.course.vo.EditSubjectFormData;
import com.two.course.vo.FenSubjectVo;
import com.two.course.vo.InsertSubjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 翟彦淇
 * @description TODO
 * @date 2022/12/7 11:43
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectDao subjectDao;

    @Override
    public Result<List<EduSubject>> getAllMenu() {
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();

        eduSubjectQueryWrapper.eq("status_id",1);

        eduSubjectQueryWrapper.eq("parent_id",0);
        List<EduSubject> eduSubjects1 = subjectDao.selectList(eduSubjectQueryWrapper);

        // 查询出来所有的title
        QueryWrapper<EduSubject> eduSubjectQueryWrapper1 = new QueryWrapper<>();
        eduSubjectQueryWrapper1.eq("status_id",1);
        List<EduSubject> eduSubjects = subjectDao.selectList(null);

        for (EduSubject record : eduSubjects1) {
            record.setChildren(findChildren(eduSubjects, record.getId()));
        }

        return new Result<>(2000,"课程分类分页查询成功",eduSubjects1);
    }

    /*==================================上面是课程中心===========================================*/


    @Override
    public Result<List<EduSubject>> findSubjectByStatus() {
        // 1. 先将所有的科目查询出来  （筛选条件status_id为1  有效  被查询出来）
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();
        eduSubjectQueryWrapper.eq("status_id","1");
        List<EduSubject> eduSubjects = subjectDao.selectList(eduSubjectQueryWrapper);
        System.out.println("eduSubjects = " + eduSubjects);
        if(eduSubjects == null){
            return new Result<>(5000,"查询全部科目失败",null);
        }
        // 2. 通过parent_id把父科目提取出来，放到list里面
        List<EduSubject> first = new ArrayList<>();
        for (EduSubject eduSubject : eduSubjects) {
            if(eduSubject.getParentId().equals("0")){
                first.add(eduSubject);
            }
        }
        // 3. 利用方法递归，来完成子科目添加到父科目的下面
        for (EduSubject eduSubject : first) {
            eduSubject.setChildren(findChildren(eduSubjects,eduSubject.getId()));
        }

        System.out.println("first = " + first);
        return new Result<>(2000,"科目查询成功",first);
    }

    @Override
    public String findPidById(String pid) {
        EduSubject eduSubject = subjectDao.selectById(pid);
        return eduSubject.getParentId();
    }


    /*==================================下面是后台代码==============上面是前台代码===========================================*/

    @Override
    @Transactional
    public Result<String> insertsubject(InsertSubjectVo insertSubjectVo) {
        EduSubject eduSubject = new EduSubject();
        eduSubject.setRemark(insertSubjectVo.getRemark());
        eduSubject.setSort(0);
        eduSubject.setTitle(insertSubjectVo.getTitle());
        eduSubject.setGmtCreate(LocalDateTime.now());
        eduSubject.setGmtModified(LocalDateTime.now());
        eduSubject.setStatusId("1");
        // 分析：去判断传过来的parentId是否为0  如果是0的话，那么就是要添加 顶级菜单  不为0  那么就是在父菜单下面添加子菜单
        // 三种添加 1. 添加一级菜单 子id：0 （雪花算法生成）   父id：0
        if(insertSubjectVo.getParentId().equals("0")&&insertSubjectVo.getId().equals("0")){
            eduSubject.setParentId("0");
            int insert = subjectDao.insert(eduSubject);
            if(insert == 0){
                return new Result<>(5000,"添加失败",null);
            }
        }
        // 2. 添加二级菜单 子id：有值 父id：0
        if(insertSubjectVo.getParentId().equals("0") && !insertSubjectVo.getId().equals("0")){
            eduSubject.setParentId(insertSubjectVo.getId());
            int insert = subjectDao.insert(eduSubject);
            if(insert == 0){
                return new Result<>(5000,"添加失败",null);
            }
        }
        // 3. 添加三级菜单 子id：有值 父id：有值
        if(!insertSubjectVo.getParentId().equals("0")&&!insertSubjectVo.getId().equals("0")){
            eduSubject.setParentId(insertSubjectVo.getId());
            int insert = subjectDao.insert(eduSubject);
            if(insert == 0){
                return new Result<>(5000,"添加失败",null);
            }
        }
        return new Result<>(2000,"成功",null);
    }

    @Override
    public Result<String> updatesubject(EditSubjectFormData editSubjectFormData) {
        // 根据传过来的  主键id 进行判断修改哪一个课程分类的内容
        EduSubject eduSubject = new EduSubject();
        eduSubject.setId(editSubjectFormData.getId());
        eduSubject.setRemark(editSubjectFormData.getRemark());
        eduSubject.setTitle(editSubjectFormData.getTitle());
        int i = subjectDao.updateById(eduSubject);
        if(i == 0){
            return new Result<>(5000,"修改失败",null);
        }
        return new Result<>(2000,"修改成功",null);
    }

    @Override
    @Transactional
    public Result<String> deletesubject(EditSubjectFormData editSubjectFormData) {
        System.out.println(editSubjectFormData);
        // 分析：先通过主键id进行删除，之后再去根据parent_id根据比对看看有没有子菜单，也要删除
        EduSubject eduSubject = new EduSubject();
        eduSubject.setId(editSubjectFormData.getId());

        int i = subjectDao.deleteById(eduSubject);
        if(i == 0){
            return new Result<>(5000,"删除一级菜单失败",null);
        }else{
            UpdateWrapper<EduSubject> eduSubjectUpdateWrapper = new UpdateWrapper<>();
            eduSubjectUpdateWrapper.eq("parent_id",editSubjectFormData.getId());
            subjectDao.delete(eduSubjectUpdateWrapper);
        }
        return new Result<>(2000,"删除成功",null);
    }

    @Override
    @Transactional
    public Result<String> changeStatusId(ChangeStatusIdVo changeStatusIdVo) {
        EduSubject eduSubject = new EduSubject();
        eduSubject.setId(changeStatusIdVo.getId());
        eduSubject.setStatusId(changeStatusIdVo.getStatusId());
        eduSubject.setParentId(changeStatusIdVo.getParentId());

        int i = subjectDao.updateById(eduSubject);
        if(i == 0){
            return new Result<>(5000,"修改一级菜单失败",null);
        }else{
            UpdateWrapper<EduSubject> eduSubjectUpdateWrapper = new UpdateWrapper<>();
            EduSubject eduSubject1 = new EduSubject();
            eduSubject1.setStatusId(changeStatusIdVo.getStatusId());
            eduSubjectUpdateWrapper.eq("parent_id",changeStatusIdVo.getId());
            int update = subjectDao.update(eduSubject1, eduSubjectUpdateWrapper);
        }
        return new Result<>(2000,"修改成功",null);
    }

    @Override
    @Transactional
    public Result<IPage<EduSubject>> findsubject(Integer pageCurrent, Integer pageSize, FenSubjectVo map) {
        // 1. 先分页查询一级菜单的条数
        IPage<EduSubject> eduSubjectIPage = new Page<>(pageCurrent,pageSize);
        // 1.1 条件 只查询出以及菜单
        QueryWrapper<EduSubject> eduSubjectQueryWrapper = new QueryWrapper<>();

        if(StringUtils.hasText(map.getTitle())){
            eduSubjectQueryWrapper.like("title",map.getTitle());
        }

        if(StringUtils.hasText(map.getStatusId())){
            eduSubjectQueryWrapper.eq("status_id",map.getStatusId());
        }

        eduSubjectQueryWrapper.eq("parent_id",0);
        IPage<EduSubject> page = subjectDao.selectPage(eduSubjectIPage, eduSubjectQueryWrapper);

        // 查询出来所有的title
        List<EduSubject> eduSubjects = subjectDao.selectList(null);

        for (EduSubject record : page.getRecords()) {
            record.setChildren(findChildren(eduSubjects, record.getId()));
        }

        return new Result<>(2000,"课程分类分页查询成功",page);
    }

    // 查找父科目下面的子科目，以及子科目下面的子科目  以及。。。。
    private List<EduSubject> findChildren(List<EduSubject> eduSubjects, String id){
        List<EduSubject> second = new ArrayList<>();
        // 整理出来二级科目
        for (EduSubject eduSubject : eduSubjects) {
            if(eduSubject.getParentId().equals(id)){
                second.add(eduSubject);
            }
        }
        // 递归调用
        for (EduSubject eduSubject : second) {
            eduSubject.setChildren(findChildren(eduSubjects,eduSubject.getId()));
        }

        return second;
    }

}
